# -*- coding: utf-8 -*-
import sys
import logging
from logging import handlers
import os
import threading
import sys
reload(sys)
sys.setdefaultencoding('utf8')


from CommonUtil import getLogFilePath
# 开发一个日志系统， 既要把日志输出到控制台， 还要写入日志文件
class Logger():

    # _instance_lock=threading.Lock()
    #
    # def __new__(cls, *args, **kwargs):
    #     if not hasattr(Logger,"_instance"):
    #         with Logger._instance_lock:
    #             if not hasattr(Logger,"_instance"):
    #                 Logger._instance=object.__new__(cls)
    #     return Logger._instance

    def __init__(self, filename=None):

        # super(MyLogger, self).__init__(self)
        # 日志文件名
        # 创建一个logger
        if filename is None:
            self.filename =getLogFilePath()
            self.logger = logging.getLogger('root')
        else:
            # filename='./logs/'+filename
            self.filename = filename
            self.logger = logging.getLogger(os.path.basename(self.filename))

        #设置logger级别
        self.logger.setLevel(logging.INFO)

        if not os.path.exists(os.path.dirname(self.filename)):
            os.mkdir(os.path.dirname(self.filename))
            pass

        # when指定单位是s(秒),interval是时间间隔的频率,单位是when所指定的哟（所以，你可以理解频率是5s）；backupCount表示备份的文件个数，我这里是指定的3个文件。
        # fh = handlers.TimedRotatingFileHandler(filename=log_file, when="S", interval=5,
        #                                        backupCount=3)  # filename定义将信息输入到指定的文件，

        # 创建一个handler，用于写入日志文件 (每天生成1个，保留30天的日志)
        fh = handlers.TimedRotatingFileHandler(self.filename, 'D', 1, 30,encoding="utf-8")
        fh.suffix = "%Y%m%d-%H%M.log"
        fh.setLevel(logging.INFO)

        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.ERROR)

        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s -%(name)s - %(filename)s[line:%(lineno)d]  - %(levelname)s - %(message)s')  # 定义输出格式
        # formater = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        #保证handler只添加一次
        self.logger.handlers = []
        # if not self.logger.handlers:
            # print("============================")
            # for handler in self.logger.handlers:
            #     print(handler)
        # 给logger添加handler
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

    def getLogger(self):
        return self.logger


def log():
    """
    打印log
    文件名+函数名,return
    :return:
    """
    def loginfo(func):
        def wrapper(*args, **kwargs):
            t = func(*args, **kwargs)
            filename = str(sys.argv[0]).split('/')[-1].split('.')[0]
            Logger().getLogger().info('{}:{}, return:{}'.format(filename, func.__name__, t))
            return t

        return wrapper

    return loginfo

def Log(filename=None):
    if filename:
        filename=filename+"/steps.log"
    return Logger(filename).getLogger()


if __name__ == '__main__':
    print Logger().getLogger().info("hahah")
    print Logger().getLogger().info("lllll")
    print Logger("D:/Test/abc.log").getLogger().info("222222")
    print Logger().getLogger().error("333333")
